package eu.jpereira.trainings.designpatterns.creational.builder.xml;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import eu.jpereira.trainings.designpatterns.creational.builder.model.ReportBody;
import eu.jpereira.trainings.designpatterns.creational.builder.model.ReportBodyBuilder;
import eu.jpereira.trainings.designpatterns.creational.builder.model.SoldItem;

public class XMLReportBodyBuilder implements ReportBodyBuilder {

	private List<SoldItem> items;
	private boolean withItems;
	private String customerPhone;
	private String customerName;
	
	public XMLReportBodyBuilder()
	{
		withItems = false;
		items = new LinkedList<SoldItem>();
	}
	
	@Override
	public void withItems() {
		withItems = true;
	}

	@Override
	public void setCustomerName(String name) {
		customerName = name;
	}

	@Override
	public void newItem(String name, int quantity, double unitPrice) {
		items.add(new SoldItem(name, quantity, unitPrice));
	}

	@Override
	public void setCustomerPhone(String phone) {
		customerPhone = phone;
	}

	@Override
	public ReportBody getReportBody() {
		XMLReportBody reportBody = new XMLReportBody();
		
		reportBody.putContent("<sale><customer><name>");
		reportBody.putContent(customerName);
		reportBody.putContent("</name><phone>");
		reportBody.putContent(customerPhone);
		reportBody.putContent("</phone></customer>");
		
		if(withItems)
		{
			reportBody.putContent("<items>");
			Iterator<SoldItem> it = items.iterator();
			while ( it.hasNext() )	
			{
				SoldItem soldEntry = it.next();
				reportBody.putContent("<item><name>");
				reportBody.putContent(soldEntry.getName());
				reportBody.putContent("</name><quantity>");
				reportBody.putContent(soldEntry.getQuantity());
				reportBody.putContent("</quantity><price>");
				reportBody.putContent(soldEntry.getUnitPrice());
				reportBody.putContent("</price></item>");
			}
			reportBody.putContent("</items>");
		}
		
		reportBody.putContent("</sale>");
		
		return reportBody;
	}

}
